package main

import (
    "context"
    "encoding/json"
    "fmt"
    "time"

    "github.com/redis/go-redis/v9"
)

var ctx = context.Background()
var Host = "redis-service.openwhisk.svc.cluster.local"
var client = redis.NewClient(&redis.Options{
    Addr:     Host + ":6380",
    Password: "123456",
    DB:       0,
})

// 定义用于解析卫星数据的结构体
type SatelliteStats struct {
    CPUPercent float64 `json:"cpuPercent"`
    MemPercent float64 `json:"memPercent"`
}

func main() {
    // 测试 Redis 连接
    pong, err := client.Ping(ctx).Result()
    if err != nil {
        panic(fmt.Sprintf("连接 Redis 失败: %v", err))
    }
    fmt.Println("Redis 连接成功:", pong)

    // 每秒更新键值
    ticker := time.NewTicker(1 * time.Second)
    defer ticker.Stop()

    for range ticker.C {
        // 获取 SatelliteState 所有哈希项
        satellites, err := client.HGetAll(ctx, "SatelliteState").Result()
        if err != nil {
            fmt.Printf("获取 SatelliteState 失败: %v\n", err)
            continue
        }

        var totalCPU, totalMem float64
        count := 0

        // 遍历所有卫星数据
        for satelliteID, value := range satellites {
            var stats SatelliteStats
            // 解析 JSON 数据
            if err := json.Unmarshal([]byte(value), &stats); err != nil {
                fmt.Printf("解析卫星 %s 数据失败: %v\n", satelliteID, err)
                continue
            }
            totalCPU += stats.CPUPercent/100.0
            totalMem += stats.MemPercent/100.0
            // 计算有效卫星数量
            count++
        }

        if count == 0 {
            fmt.Println("没有有效的卫星数据")
        }
        var avgCPU= 0.0
        var avgMem= 0.0
        // 计算平均值
        if(count > 0) {
           fmt.Printf("有效卫星数量: %d\n", count)
            // 计算平均 CPU 和内存使用率
           avgCPU = totalCPU / float64(count)
           avgMem = totalMem / float64(count)
        }
        // 存储平均值到 Redis
        if _, err := client.Set(ctx, "AverageCPU", avgCPU, 0).Result(); err != nil {
            fmt.Printf("存储 AverageCPU 失败: %v\n", err)
        }
        if _, err := client.Set(ctx, "AverageMem", avgMem, 0).Result(); err != nil {
            fmt.Printf("存储 AverageMem 失败: %v\n", err)
        }

        fmt.Printf("更新平均值: CPU %.2f%%, Mem %.2f%%\n", avgCPU*100, avgMem*100)
    }
}